/*
 * @Author: Jan-superman
 * @Date: 2018-09-03 21:39:16
 * @Last Modified by: Jan-superman
 * @Last Modified time: 2018-09-07 21:53:45
 * 通用加签相关封装
 */

import md5 from 'js-md5'
import { stringify } from 'qs'


const APP_KEY = "5d3961603c3a6a8d7fc27b68"
const APP_SECRET = "56d91b6eaa1c5ee858770bff09b72e45"

const defString = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

// 随机字符串
const randomString = length => {
  let result = ''
  for (let i = length; i > 0; --i) {
    result += defString[Math.round(Math.random() * (defString.length - 1))]
  }
  return result
}

// 排序
const sort = arrays => {
  const newKey = Object.keys(arrays).sort()
  const newObj = {}
  for (let i = 0; i < newKey.length; i++) {
    newObj[newKey[i]] = arrays[newKey[i]]
  }
  return newObj
}

class CreateSign {
  constructor() {
    this.TS = Date.now()
    this.CODE = randomString(6)
  }

  // sign 计算方法,接收参数对象
  createMd5Sign = obj => {
    if (obj) {
      obj = stringify(sort(obj))
    } else {
      obj = ''
    }
    const o = [
      APP_KEY,
      decodeURIComponent(obj),
      this.TS,
      this.CODE,
      APP_SECRET
    ]
    return md5(o.join('&'))
  };
}

export default CreateSign
export { APP_KEY, APP_SECRET, randomString }
